#!/usr/bin/python3

import os
import glob
import diffSymbolDB
import subprocess

currentDir=os.getcwd()+'/vsroot'

usrlib='/usr/lib'
usrlib64='/usr/lib64'
lib='/lib'
lib64='/lib64'

osversion='cen7.0'


def filterRpmName(rpmname):
    return ".x86_64.rpm" in rpmname


def decompressionRpmFile(rpmpath):
    cmd='rpm2cpio {} | cpio -div -D {}'.format(rpmpath,currentDir)
    os.system(cmd)

def execCmd(cmd):
    process = subprocess.Popen([cmd],shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()

    strResult = stdout.strip().decode('utf-8') if hasattr(stdout, 'decode') else stdout.strip() 
    return strResult

def scanVSrootDir(directory):
    files = []
    if not os.path.exists(directory):
        return files
    for item in os.listdir(directory):  
        full_path = os.path.join(directory, item)  
        if not os.path.isdir(full_path): 
            files.append(item) 
    return files  

def dailfileinsert2DB(path,rpmpackagename,osversion):
    print("csan dir {}{}".format(currentDir,path))
    filelist=scanVSrootDir('{}{}'.format(currentDir,path))
    for file in filelist:
        linkfile=currentDir+path+'/'+file
        is_link=0
        if os.path.islink(currentDir+path+'/'+file):
            linkfile=os.path.realpath(currentDir+path+'/'+file)
            is_link=1
        print("insert path {} {}".format(path,linkfile[len(currentDir):]))
        diffSymbolDB.insertLibRpmPakcageRelevanceValue2Table(path+'/'+file,rpmpackagename,is_link,linkfile[len(currentDir):],osversion,"cen")


def caleSoLibCount(rpmpath):
    libsize=execCmd("""rpm -qpl {} |grep ^/usr/lib/[^/]*\.so |wc -l""".format(rpmpath))
    lib64size=execCmd("""rpm -qpl {} |grep ^/usr/lib64/[^/]*\.so  |wc -l""".format(rpmpath))
    libEx=execCmd("""rpm -qpl {} |grep ^/lib/[^/]*\.so  |wc -l""".format(rpmpath))
    lib64Ex=execCmd("""rpm -qpl {} |grep ^/lib64/[^/]*\.so  |wc -l""".format(rpmpath))
    print("libsize {} lib64size {} libEx {} lib64Ex {}".format(libsize, lib64size,libEx,lib64Ex))
    if libsize != '0' or  lib64size !='0' or libEx != '0' or lib64Ex != '0':
        return True
    else:
        return False


def parseRpmFileInfo(rpmlist):
    for item in rpmlist:
        print(item)
        if caleSoLibCount(item):
            decompressionRpmFile(item)
            rpmfile = os.path.basename(item)
            dailfileinsert2DB(usrlib64,rpmfile,osversion)
            dailfileinsert2DB(usrlib,rpmfile,osversion)
            dailfileinsert2DB(lib64,rpmfile,osversion)
            dailfileinsert2DB(lib,rpmfile,osversion)
            os.system('rm -rf {}/*'.format(currentDir))

def scanBaseOSDir(path):
    filelist=glob.glob(path)
    return list(filter(filterRpmName,filelist))


def analysisRpmPackageFiles(BaseOSpath):
    rpmlist=scanBaseOSDir(BaseOSpath)
    parseRpmFileInfo(rpmlist)